/**
 * Copyright (c) 2015-2019, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.web.theme;

import cn.hg.jfsa.core.ControllerThreadLocal;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.render.ErrorRender;
import com.jfinal.render.Render;
import com.jfinal.render.RenderFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Golly
 *
 */
public class ThemeRenderFactory extends RenderFactory {

	private List<String> excludeViewPostfixList = new ArrayList<String>();

	public ThemeRenderFactory(String... excludeViewPostfixs) {
		// Error页面需要排除掉一些页面前缀
		for (String prefix : excludeViewPostfixs) {
			excludeViewPostfixList.add(prefix);
		}
	}

	@Override
	public Render getErrorRender(int errorCode, String view) {
		Controller c = ControllerThreadLocal.get();
		if (c != null) {
			String actionKey = c.getRequest().getRequestURI();
			actionKey = new String(actionKey.replaceAll(c.getRequest().getContextPath(), ""));
			// 如果没有被排除，则当前action为Web主题页面
			if (!isExclude(actionKey)) {
				Theme theme = ThemeManager.me().getCurrentTheme();
				return new ThemeRender(view);
			}
		}
		return new ErrorRender(errorCode, view);
	}

	@Override
	public Render getErrorRender(int errorCode) {
		Controller c = ControllerThreadLocal.get();
		if (c != null) {
			String actionKey = c.getRequest().getRequestURI();
			actionKey = new String(actionKey.replaceAll(c.getRequest().getContextPath(), ""));
			// 如果没有被排除，则当前action为Web主题页面
			if (!isExclude(actionKey)) {
				Theme theme = ThemeManager.me().getCurrentTheme();
				String errorView = theme.getErrorViewMap().get(errorCode);
				if (StrKit.notBlank(errorView)) { // 如果Error页面已经在主题配置文件中
					return new ThemeRender(errorView);
				} else if (StrKit.notBlank(theme.getErrorViewMap().get(0))) { // 如果主题配置文件中设置了通用Error页面
					return new ThemeRender(theme.getErrorViewMap().get(0));
				}
			}

		}
		return new ErrorRender(errorCode, constants.getErrorView(errorCode));
	}

	private boolean isExclude(String actionKey) {
		for (String prefix : this.excludeViewPostfixList) {
			if (actionKey.startsWith(prefix)) {
				return true;
			}
		}

		return false;
	}
}
